<script lang="ts" setup>
import {ref, reactive, inject, type Ref} from 'vue';
import {type Router, useRouter} from "vue-router";
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue';
import { postUserLogin} from "@/apis/student";
import {type FormInstance, message} from 'ant-design-vue';
import type { Rule } from 'ant-design-vue/es/form';
import {type FormState, regexRule} from "./setting";
import type {TResult} from "@/config";
import Vcode from "vue3-puzzle-vcode";

const go:any = inject('go')
const router:Router = useRouter()
const formRef:Ref = ref<FormInstance>();
const formState = reactive<FormState>({
  username: '',
  password: '',
  remember: true,
});
// 验证码弹框
//验证框图片设置
const imgs:Array<any>=['https://picsum.photos/200/300']
let showVcode = ref<boolean>(false)
const onShow = () => {
  showVcode.value = true;
};
const onClose = () => {
  showVcode.value = false;
};
const onSuccess = async () => {
  //发送请求，请求登录
  const res:TResult<boolean> = await postUserLogin({
    userName: formState.username,
    userPassword: formState.password
  })
  if(res && res.status == 200){
    if(res.data){
      await router.push('/login-midd/'+res.data)  //这是用户关键信息token，非用户信息
      // await router.push('/student')
    }else {
      message.success("暂时没有权限登录哦.")
    }
  }
  else {
    message.error("登录失败，请查看网络是否连接")
  }
  onClose(); // 验证成功，手动关闭模态框
};
const onFinish = async (values: FormState) => {
  // const {username, password} = values
  onShow()
};
const onFinishFailed = (errorInfo: any):void => {
  const {errorFields} = errorInfo
  message.error(`错误：${errorFields.map(({name}:any):string => name)}`,1)
};
//自定义校验规则
const validateName = async (_rule: Rule, value: string) => {
  if (!value){
    return Promise.reject('请输入账户');
  }
  if (!regexRule.uname.test(value)){
    return Promise.reject('3-16位数字与字母');
  }else {
    return Promise.resolve();
  }
};
const validatePass = async (_rule: Rule, value: string) => {
  if (!value){
    return Promise.reject('请输入密码');
  }
  if (!regexRule.pwd.test(value)){
    return Promise.reject('6位以上字符且包含数字、字母');
  }else {
    return Promise.resolve();
  }
};
const rules: Record<string, Rule[]> = {
  username: [{ required: true, validator: validateName, trigger: 'change' }],
  password: [{ required: true, validator: validatePass, trigger: 'change' }],
};
</script>

<template>
  <a-flex justify="end">
    <a-button type="link" @click="go('/')">返回</a-button>
  </a-flex>
  <div class="form-body">
    <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        name="normal_login"
        class="login-form"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
    >
      <a-form-item
          label="账号"
          name="username"
          has-feedback
      >
        <a-input v-model:value="formState.username">
          <template #prefix>
            <UserOutlined class="site-form-item-icon" />
          </template>
        </a-input>
      </a-form-item>

      <a-form-item
          label="密码"
          name="password"
          has-feedback
      >
        <a-input-password v-model:value="formState.password">
          <template #prefix>
            <LockOutlined class="site-form-item-icon" />
          </template>
        </a-input-password>
      </a-form-item>

      <a-form-item>
        <a-form-item name="remember" no-style>
          <a-checkbox v-model:checked="formState.remember">记住密码</a-checkbox>
        </a-form-item>
        <a-button type="link" class="login-form-forgot" @click="go('/forget')">忘记密码？</a-button>
      </a-form-item>

      <a-form-item>
        <a-button type="primary" html-type="submit" class="login-form-button">
          登 录
        </a-button>
        <Vcode :show="showVcode" @success="onSuccess" @close="onClose" :imgs="imgs" :sliderSize="36"></Vcode>
        <a-button type="link" @click="go('/register')">注册账号</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<style lang="scss" scoped>
.login-form {
  max-width: 300px;
  margin: 0 auto;
}
.login-form-forgot {
  float: right;
}
.login-form-button {
  width: 100%;
}
.form-body{
  height: 100%;
  margin: 0;
  box-sizing: border-box;
  padding: 1rem;
  display: flex;
  align-items: center;
}
</style>
